﻿using iTool.ClusterComponent;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;

namespace iTool.ClusterComponent
{
    public class OrderlyWorkUnitProvider : IWorkUnitProvider
    {
        public IWorkScopeProvider WorkScopeProvider { get; }
        public ILockService LockService { get; }
        public OrderlyWorkUnitProvider(IWorkScopeProvider workScopeProvider) 
        {
            this.WorkScopeProvider = workScopeProvider;
            this.LockService = this.GetLockService();
        }

        public Task ApplyExcuterAsync() => this.LockService.GetLockAsync();

        public void Dispose()
        {
            _ = this.DisposeAsync();
        }

        public async ValueTask DisposeAsync()
        {
            await this.WorkScopeProvider.NextAsync();
            await this.LockService.FreedLockAsync();
            GC.SuppressFinalize(this);
        }


        private ILockService GetLockService() 
        {
            return this.WorkScopeProvider.ClusterService.GetService<ILockService>(this.WorkScopeProvider.WorkScopeName);
        }
    }
}
